<template>
  <md-popup :value="true" position="bottom" :has-mask="false" prevent-scroll id="mapview">
    <div class="container">
      <div id="searcher">
        <div class="city-name" @click="selectCity" v-if="!selectCityMode">
          <div>{{selectedCity.name}}</div>
          <md-icon name="city_next" style="width:18px;height:8px;margin-left:8px;"></md-icon>
        </div>
        <md-input-item
          @focus="onCitySearcherFocus"
          type="text"
          v-model="cityValue"
          class="city-input"
          ref="cityInput"
          :placeholder="'请输入城市'"
          v-if="selectCityMode"
        >
          <md-icon name="clear_icon" slot="right" v-show="cityValue!=''" @click="clearCityValue"></md-icon>
        </md-input-item>
        <md-input-item
          @focus="onPoiSearcherFocus"
          type="text"
          v-model="searchValue"
          class="searcher-input"
          ref="searcherInput"
          :placeholder="hintString"
        >
          <md-icon name="clear_icon" slot="right" v-show="searchValue!=''" @click="clearSearchValue"></md-icon>
        </md-input-item>
        <div class="searcher-btn" @click="cancel">取消</div>
      </div>
      <amap
        class="amap"
        ref="amap"
        :center="currentLocation.coordinate"
        :zoom="15"
        @complete="onMapComplete"
        @select="onMapSelect"
        @dragstart="onMapStartDrag"
      ></amap>
      <div id="search-result" v-if="selectedAddress">
        <img :src="isStart?syncStartIcon:syncEndIcon" class="sync-icon" />
        <div class="address-field">
          <div class="row centered">
            <div class="main-string text-ellipsis">{{selectedAddress.stationName}}</div>
            <div v-if="selectedAddress.stationId" class="tag">乘车点</div>
          </div>
          <div class="sub-string text-ellipsis">{{selectedAddress.position}}</div>
        </div>
        <md-button class="confirm-btn" @click="confirm">确定</md-button>
      </div>
      <search-box v-if="showBox" :searchs="searchList" v-model="searchValue" @select="onItemSelect"></search-box>
      <hitch-city-list
        v-if="selectCityMode"
        :searchValue="cityValue"
        :currentLocation="currentLocation"
        @submit="onCitySubmit"
        @ready="onCityListReady"
      ></hitch-city-list>
    </div>
  </md-popup>
</template>
<script>
import '@/assets/svgs/clear_icon.svg';
import '@/assets/svgs/city_next.svg';
import { Popup, Button, Icon, InputItem } from 'mand-mobile';
import MapTool from '@/components/map/MapTool';
import SearchBox from '@/components/map/search/SearchBox';
import HitchCityList from './HitchCityList';
import { createNamespacedHelpers } from 'vuex';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
const { mapActions, mapGetters } = createNamespacedHelpers('hitchhike');
export default {
  name: 'position-selector',
  components: {
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [InputItem.name]: InputItem,
    SearchBox,
    HitchCityList,
    [MapTool.name]: MapTool
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    isStart: {
      type: Boolean,
      default: true
    },
    appendTo: {
      default: () => document.body
    }
  },
  watch: {
    searchValue: 'onValueChange'
  },
  data() {
    return {
      searchValue: '',
      syncStartIcon: require('@/assets/imgs/snyc_shangche_icon.png'),
      syncEndIcon: require('@/assets/imgs/snyc_xiache_icon.png'),
      selectedAddress: null,
      showBox: false,
      autoComplete: null,
      searchList: null,
      isItemFromList: false,
      currentLocation: null,
      cityValue: '',
      selectCityMode: false,
      selectedCity: {}
    };
  },
  created() {
    this.currentLocation = this.$store.getters.getCurrentLocation;
    this.selectedCity.name = this.currentLocation.provinceName;
    AMap.plugin('AMap.Autocomplete', () => {
      let autoOptions = {
        city: this.currentLocation.provinceCode,
        citylimit: true
      };
      this.autoComplete = new AMap.Autocomplete(autoOptions);
    });
  },
  mounted() {
    if (this.appendTo) {
      this.appendTo.appendChild(this.$el);
    }
  },
  beforeDestroy() {
    if (this.appendTo) {
      this.appendTo.removeChild(this.$el);
    }
  },
  methods: {
    ...mapActions(['getAdsorptionInfo']),
    onMapComplete() {
      this.$refs.amap.initPositionPicker();
    },
    onMapSelect(item) {
      if (item.adsorption) {
        if (this.isItemFromList) {
          item.stationName = this.selectedAddress.stationName;
          item.position = this.selectedAddress.position;
        }
        this.selectedAddress = item;
        this.$refs.amap.createTextTip(item.coordinate, this.isStart ? '在这里上车' : '在这里下车');
        return;
      }
      this.getAdsorptionInfo({
        isStart: this.isStart,
        coord: this.coordToString(item.coordinate)
      }).then(res => {
        console.log(res);
        if (res && JSON.stringify(res) != '{}') {
          if (res.adsorption && res.adsorption instanceof Array) {
            if (res.adsorption.length >= 1) {
              res.adsorption.forEach((item, index) => {
                res.adsorption[index].lnglat = decryptByDESModeEBC(item.lnglat);
              });
              this.$refs.amap.createAdsorptionMarkers(res.adsorption, res.siteId);
            }
          }
          if (res.fence != undefined && res.fence != '') {
            // 有吸附点围栏，进行吸附处理
            this.$refs.amap.createAdsorptionFence(res.fence);
          }
          if (res.city != undefined && res.city != '') {
            this.cityInfo = res.city;
          }
        } else {
          // 没有吸附点围栏，无需处理
          this.selectedAddress = item;
          this.$refs.amap.createTextTip(
            item.coordinate,
            this.isStart ? '在这里上车' : '在这里下车'
          );
          this.$refs.amap.clearAdsorption();
        }
      });
    },
    onMapStartDrag() {
      this.isItemFromList = false;
      this.$refs.amap.closeTextTip();
    },
    onSearcherFocus(event) {
      this.showBox = true;
    },
    cancel() {
      if (this.selectCityMode) {
        this.selectCityMode = false;
      } else if (this.showBox) {
        this.showBox = false;
      } else {
        this.value = false;
        this.$emit('cancel');
      }
    },
    onItemSelect(item) {
      this.showBox = false;
      this.$refs.amap.setCenter(item.coordinate);
      this.selectedAddress = item;
      this.isItemFromList = true;
      this.searchValue = '';
    },
    onValueChange(value) {
      if (!this.autoComplete) {
        return;
      }
      this.autoComplete.search(value, (status, result) => {
        if (typeof result !== 'string') {
          if (result.tips && result.tips.length > 0) {
            let arr = [];
            result.tips.forEach((item, index) => {
              if (!item.location) {
                return;
              }
              let obj = {
                stationName: item.name,
                position: item.district + item.address,
                coordinate: [item.location.lng, item.location.lat]
              };
              arr.push(obj);
            });
            this.searchList = arr;
          }
        }
      });
    },
    confirm() {
      this.$emit('submit', { address: this.selectedAddress, city: this.cityInfo });
    },
    coordToString(coordinate) {
      return coordinate[0] + ',' + coordinate[1];
    },
    clearCityValue() {
      this.cityValue = '';
    },
    clearSearchValue() {
      this.searchValue = '';
    },
    selectCity() {
      this.selectCityMode = true;
      if (this.$refs.cityInput) {
        this.$refs.cityInput.focus();
      }
    },
    onCitySubmit(city) {
      console.log('选择的城市信息：', city);
      this.selectedCity = city;
      this.changeAutoCompleteOption(city.adcode);
      this.selectCityMode = false;
    },
    changeAutoCompleteOption(cityCode) {
      if (this.autoComplete) {
        this.autoComplete.setCity(cityCode);
        this.autoComplete.setCityLimit(true);
      }
    },
    onPoiSearcherFocus() {
      this.showBox = true;
      this.selectCityMode = false;
    },
    onCitySearcherFocus() {
      this.showBox = false;
      this.selectCityMode = true;
    },
    onCityListReady() {
      if (this.$refs.cityInput) {
        this.$refs.cityInput.focus();
      }
    }
  },
  computed: {
    hintString() {
      return this.isStart ? '您从哪儿上车' : '您要去哪儿';
    }
  }
};
</script>
<style lang="stylus">
#mapview {
  .md-popup-mask {
    z-index: 100;
  }

  .container {
    width: 100vw;
    height: 100vh;
    background-color: #fff;

    .amap {
      width: 100vw;
      height: calc(100vh - 88px);
    }

    #searcher {
      background-color: #F8F8F8;
      font-size: 28px;
      height: 100px;
      padding-left: 30px;
      padding-right: 30px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;

      .city-name {
        min-width: 3em;
        max-width: 8em;
        color: #666;
        padding-right: 20px;
        border-right: 1px solid #E0E0E0;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
      }

      .city-input {
        border: 0px;
        outline: none;
        background-color: transparent;
        width: 5em;
        font-size: 28px;
      }

      .searcher-input {
        padding-left: 20px;
        border: 0px;
        outline: none;
        background-color: transparent;
        flex: 1;
        font-size: 26px;
        height: 88px;
      }

      .searcher-btn {
        color: #888888;
        padding-left: 20px;
        font-size: 26px;
      }
    }

    #search-result {
      width: 710px;
      height: 120px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: fixed;
      background-color: #fff;
      bottom: 20px;
      left: 20px;

      .sync-icon {
        width: 40px;
        height: 48px;
        margin-left: 20px;
      }

      .address-field {
        flex: 1;
        margin-left: 20px;

        .main-string {
          font-size: 26px;
          font-weight: 400;
          max-width: 16em;
          color: color-text-base;
        }

        .tag {
          background-color: #FF6917;
          width: 72px;
          height: 28px;
          color: #fff;
          font-size: 20px;
          line-height: 28px;
          margin-left: 10px;
          text-align: center;
          border-radius: 4px;
          padding: 0px 6px;
          vertical-align: middle;
        }

        .sub-string {
          font-size: 22px;
          font-weight: 400;
          max-width: 20em;
          color: color-text-caption;
        }
      }

      .confirm-btn {
        width: 160px;
        height: 68px;
        font-size: 30px;
        margin-right: 20px;
      }
    }
  }
}
</style>